﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace App_Clinique.ClassLibrary.Classes
{
    public static class AesRjindael
    {
        public static void EncryptFile(string strKey, string strIv, string pathPlainTextFile, string pathCypheredTextFile)
        {
            // Place la clé de déchiffrement dans un tableau d'octets
            byte[] key = Encoding.UTF8.GetBytes(strKey);

            // Place le vecteur d'initialisation dans un tableau d'octets
            byte[] iv = Encoding.UTF8.GetBytes(strIv);

            FileStream fsCypheredFile = new FileStream(pathCypheredTextFile, FileMode.Create);

            RijndaelManaged rijndael = new RijndaelManaged();
            rijndael.Mode = CipherMode.CBC;
            rijndael.Key = key;
            rijndael.IV = iv;


            ICryptoTransform aesEncryptor = rijndael.CreateEncryptor();

            CryptoStream cs = new CryptoStream(fsCypheredFile, aesEncryptor, CryptoStreamMode.Write);

            FileStream fsPlainTextFile = new FileStream(pathPlainTextFile, FileMode.OpenOrCreate);

            int data;

            while ((data = fsPlainTextFile.ReadByte()) != -1)
            {
                cs.WriteByte((byte)data);
            }

            fsPlainTextFile.Close();
            cs.Close();
            fsCypheredFile.Close();
        }

        public static void DecryptFile(string strKey, string strIv, string pathCypheredTextFile, string pathPlainTextFile)
        {
            // Place la clé de déchiffrement dans un tableau d'octets
            byte[] key = Encoding.UTF8.GetBytes(strKey);

            // Place le vecteur d'initialisation dans un tableau d'octets
            byte[] iv = Encoding.UTF8.GetBytes(strIv);

            // Filestream of the new file that will be decrypted.   
            FileStream fsCrypt = new FileStream(pathPlainTextFile, FileMode.Create);

            RijndaelManaged rijndael = new RijndaelManaged();
            rijndael.Mode = CipherMode.CBC;
            rijndael.Key = key;
            rijndael.IV = iv;


            ICryptoTransform aesDecryptor = rijndael.CreateDecryptor();

            CryptoStream cs = new CryptoStream(fsCrypt, aesDecryptor, CryptoStreamMode.Write);

            // FileStream of the file that is currently encrypted.    
            FileStream fsIn = new FileStream(pathCypheredTextFile, FileMode.OpenOrCreate);

            int data;

            while ((data = fsIn.ReadByte()) != -1)
            {
                cs.WriteByte((byte)data);
            }

            cs.Close();
            fsIn.Close();
            fsCrypt.Close();

        }
    }
}
